//
//  SQLiteTool.m
//  UI18_Work 数据库
//
//  Created by dllo on 16/8/8.
//  Copyright © 2016年 yh. All rights reserved.
//

#import "SQLiteTool.h"
#import "Person.h"
@implementation SQLiteTool

+ (SQLiteTool *)sharedSQLiteTool {
    static SQLiteTool *tool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[SQLiteTool alloc] init];
    });
    return tool;
}

- (BOOL)openSQLite3 {
    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [sandBox firstObject];
    NSString *dbPath = [path stringByAppendingPathComponent:@"contact.db"];
    NSLog(@"%@", dbPath);
    int result = sqlite3_open([dbPath UTF8String], &dbPoint);
    return [self isResult:result text:@"打开数据库"];
}

- (BOOL)createTable {
NSString *tableSQL = @"create table contact(name text, address text, phoneNumber text)";
    int result = sqlite3_exec(dbPoint, [tableSQL UTF8String], NULL, NULL, NULL);
    return [self isResult:result text:@"创建表"];
}

- (BOOL)insertContact:(Person *)contact {
    NSString *insertSQL = [NSString stringWithFormat:@"insert into contact values ('%@', '%@', '%@')", contact.name, contact.address, contact.phoneNumber];
    int result = sqlite3_exec(dbPoint, [insertSQL UTF8String], NULL, NULL, NULL);
    
    return [self isResult:result text:@"插入数据"];
}

- (__kindof NSArray *)selectAll {
    sqlite3_stmt *stmt = NULL;
    NSString *selectSQL = @"select * from contact";
    int result = sqlite3_prepare(dbPoint, [selectSQL UTF8String], -1, &stmt, NULL);
    NSMutableArray *perArray = [NSMutableArray array];
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
//            const unsigned char *picImage = sqlite3_column_text(stmt, 0);
            const unsigned char *name = sqlite3_column_text(stmt, 0);
            const unsigned char *address = sqlite3_column_text(stmt, 1);
            const unsigned char *phoneNumber = sqlite3_column_text(stmt, 2);
            Person *contact = [Person new];
//            contact.picImage = [NSString stringWithUTF8String:(const char *) picImage];
            contact.name = [NSString stringWithUTF8String:(const char *) name];
            contact.address = [NSString stringWithUTF8String:(const char *) address];
            contact.phoneNumber = [NSString stringWithUTF8String:(const char *) phoneNumber];
            [perArray addObject:contact];
        }
    }
    return perArray;
}

- (BOOL)deleteAll {
    NSString *deleteSQL = @"delete from contact where 1=1";
    int result = sqlite3_exec(dbPoint, [deleteSQL UTF8String], NULL, NULL, NULL);
    return [self isResult:result text:@"删除"];
}




- (BOOL)isResult:(int)result text:(NSString *)text {
    BOOL a = YES;
    if (result == SQLITE_OK) {
        NSLog(@"%@成功", text);
    } else {
        NSLog(@"%@失败", text);
    }
    return a;
}














@end
